#include "Segmentation.h"
#include "time.h"

IplImage* Segmentation::K_means(int* means, int& k, MyImage* im)
{
	CvSize size = cvSize(im->width, im->height);
	IplImage* newIm = cvCreateImage(size,im->depth,1);	
	double* Pixels = im->GetPlane()->GetPlaneAdress();
	byte* newPixels = (uchar*)newIm->imageData;
	double* sum = new double[k];
	int* numbers = new int[k];
	double* newK = new double[k];

	memset(numbers, 0, sizeof(int)*k);
	memset(sum, 0, sizeof(double)*k);

	int sizeP = im->GetPlane()->GetSize();
	double min = 0;
	byte meanJ = 0;
	byte val = 0;
	for(int i = 0; i < sizeP; ++i)
	{
		min = 10000000;
		meanJ = 0;
		for(int j = 0; j < k; ++j)
		{
			if (fabs(Pixels[i]-(means[j]/255.))<min)
			{
				min = fabs(Pixels[i]-means[j]/255.);
				meanJ = j;
			}
			
		}
		sum[meanJ] += Pixels[i];
		++(numbers[meanJ]);
		newPixels[i] = meanJ;
	}
	//for (int i = 0; i<k; i++)
	//{
	//	if (numbers[i]!=0)
	//	{		
	//		newK[i] = sum[i]/numbers[i];
	//	}


	//}

	delete[] numbers;
	delete[] newK;
	delete[] sum;

	return newIm;
}